package api

import (
	"fmt"
	"net/http"
	"shop/internal/models"
	"shop/internal/service/weixinuser_service"
	"shop/pkg/app"
	"shop/pkg/constant"
	"shop/pkg/global"

	"github.com/gin-gonic/gin"
	"github.com/unknwon/com"
)

type UserController struct{}

// 用户详情 - GET 请求
func (e *UserController) Info(c *gin.Context) {
	var (
		appG = app.Gin{C: c}
	)
	id := com.StrTo(c.Param("id")).MustInt64()
	global.LOG.Info(id)

	userInfo := weixinuser_service.User{Id: id}
	userResult := userInfo.GetUserInfo()
	if userResult.Content == nil {
		appG.Response(http.StatusNotFound, constant.ERROR, "用户不存在")
		return
	}

	appG.Response(http.StatusOK, constant.SUCCESS, userResult.Content)

}

// 更新用户数据
func (e *UserController) UpdateUser(c *gin.Context) {

	var (
		appG  = app.Gin{C: c}
		udata models.ShopUser // 改为值类型，不是指针类型
	)
	fmt.Printf("=== 路由调试 ===\n")
	fmt.Printf("请求路径: %s\n", c.Request.URL.Path)
	fmt.Printf("完整URL: %s\n", c.Request.URL.String())
	fmt.Printf("查询参数: %v\n", c.Request.URL.Query())

	httpCode, errCode := app.BindAndValid(c, &udata)
	fmt.Printf("绑定结果: httpCode=%d, errCode=%d\n", httpCode, errCode)
	fmt.Printf("绑定后的req.Id: %d\n", udata.Id)

	if errCode != constant.SUCCESS {
		appG.Response(httpCode, errCode, nil)
		return
	}

	// 确保用户ID存在
	if udata.Id == 0 {
		appG.Response(http.StatusBadRequest, constant.INVALID_PARAMS, "用户ID不能为空")
		return
	}

	Data := &models.ShopUser{
		BaseModel: models.BaseModel{Id: udata.Id}, // 正确设置嵌入结构体的 Id 字段
		// 主键ID必须包含
		Username: udata.Username,
		RealName: udata.RealName,
		// Birthday: udata.Birthday,
		// CardId:   udata.CardId,
		Phone:      udata.Phone,
		Nickname:   udata.Nickname,
		Avatar:     udata.Avatar,
		SessionKey: udata.SessionKey, // session_key
	}

	userData := weixinuser_service.User{
		M: Data,
	}
	err := userData.UpdateUserInfo()
	if err != nil {
		appG.Response(http.StatusOK, constant.SUCCESS, err)
	}
	appG.Response(http.StatusOK, constant.SUCCESS, nil)
}
